package com.relife.common.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import com.alibaba.fastjson.JSONObject;
import com.relife.common.utils.StringUtil;
import com.relife.common.utils.SysConfig;
import com.relife.common.utils.XmlUtil;
import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



public class HttpUtil {
	private static final Logger log = Logger.getLogger(HttpUtil.class);

	/**
	 * https 请求
	 * 
	 * @author WU
	 * @date 2015-6-9 下午7:30:49
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject obj = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			log.info("返回结果：" + buffer.toString());
			obj = JSONObject.parseObject(buffer.toString());
		} catch (ConnectException ce) {
			log.error("*****服务器请求超时******");
		} catch (Exception e) {
			log.error("https 请求失败：\n" + StringUtil.exception2String(e));
		}
		return obj;
	}

	public static Map<String, String> HttpRequest(String reqUrl, String method, String out) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(reqUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(method);

			if ("GET".equalsIgnoreCase(method))
				httpUrlConn.connect();
			if (StringUtil.isNotEmpty(out)) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(out.getBytes("UTF-8"));
				outputStream.flush();
				outputStream.close();
			}
			InputStream inputStream = httpUrlConn.getInputStream();
			map = XmlUtil.parseXml(inputStream);
			httpUrlConn.disconnect();
		} catch (Exception e) {
			log.error("https 请求失败：\n" + StringUtil.exception2String(e));
		}
		return map;
	}

	/**
	 * 
	 * @author WU
	 * @date 2015年9月13日 下午10:50:24
	 * @param strUrl
	 * @param method
	 * @param out
	 * @return
	 * @throws Exception
	 */
	public static String request(String strUrl, String method, String out) throws Exception {
		URL url = new URL(strUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(method);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setConnectTimeout(20 * 1000);// 设置访问超时时间为2秒
		conn.setUseCaches(false);
		conn.addRequestProperty("Content-Type", "application/json");

		if ("GET".equalsIgnoreCase(method)) {
			conn.connect();
		}

		if (StringUtil.isNotEmpty(out)) {
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(out.getBytes("UTF-8"));
			outputStream.flush();
			outputStream.close();
		}

		InputStream in = conn.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
		StringBuffer str = new StringBuffer();
		String line = bufferedReader.readLine();
		while (line != null) {
			str.append(line);
			line = bufferedReader.readLine();
		}
		bufferedReader.close();
		return str.toString();
	}

	/**
	 * SpringMvc下获取request
	 * 
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (servletRequestAttributes != null) {
			return servletRequestAttributes.getRequest();
		} else {
			return null;
		}
	}

	/**
	 * SpringMvc下获取session
	 * 
	 * @return
	 */
	public static HttpSession getSession() {
		HttpServletRequest request = getRequest();
		if (request == null) {
			return null;
		} else {
			return request.getSession();
		}
	}

	/**
	 * 获取IP
	 * 
	 * @author WU
	 * @date 2015-5-17 下午9:25:07
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.indexOf(",") != -1) {
			ip = ip.substring(0, ip.indexOf(","));
		}
		return ip;
	}

	/**
	 * 
	 * @return
	 */
	public static String getIpAddr() {
		return getIpAddr(HttpUtil.getRequest());
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年7月14日 下午3:10:27
	 * @return
	 */
	public static String getUrl() {
		String url = SysConfig.getProperty("domain_name") + HttpUtil.getRequest().getRequestURI().substring(1);
		String queryStr = HttpUtil.getRequest().getQueryString();
		if (queryStr != null && !"".equals(queryStr)) {
			url += "?" + queryStr;
		}
		return url;
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年5月30日 下午5:44:22
	 * @param name
	 * @return
	 */
	public static String getCookie(String name) {
		Cookie[] cookies = HttpUtil.getRequest().getCookies();
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName()) && StringUtil.isNotEmpty(cookie.getValue())) {
				return cookie.getValue();
			}
		}
		return null;
	}

}
